/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
import CryptoJS from "crypto-js";
export function parseTime(time, cFormat) {
    if (arguments.length === 0 || !time) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string')) {
            if ((/^[0-9]+$/.test(time))) {
                // support "1548221490638"
                time = parseInt(time)
            } else {
                // support safari
                // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
                time = time.replace(new RegExp(/-/gm), '/')
            }
        }

        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
            // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
        return value.toString().padStart(2, '0')
    })
    return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
    if (('' + time).length === 10) {
        time = parseInt(time) * 1000
    } else {
        time = +time
    }
    const d = new Date(time)
    const now = Date.now()

    const diff = (now - d) / 1000

    if (diff < 30) {
        return '刚刚'
    } else if (diff < 3600) {
        // less 1 hour
        return Math.ceil(diff / 60) + '分钟前'
    } else if (diff < 3600 * 24) {
        return Math.ceil(diff / 3600) + '小时前'
    } else if (diff < 3600 * 24 * 2) {
        return '1天前'
    }
    if (option) {
        return parseTime(time, option)
    } else {
        return (
            d.getMonth() +
            1 +
            '月' +
            d.getDate() +
            '日' +
            d.getHours() +
            '时' +
            d.getMinutes() +
            '分'
        )
    }
}
/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
    let timeout, args, context, timestamp, result

    const later = function() {
        // 据上一次触发时间间隔
        const last = +new Date() - timestamp

        // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
        if (last < wait && last > 0) {
            timeout = setTimeout(later, wait - last)
        } else {
            timeout = null
                // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
            if (!immediate) {
                result = func.apply(context, args)
                if (!timeout) context = args = null
            }
        }
    }

    return function(...args) {
        context = this
        timestamp = +new Date()
        const callNow = immediate && !timeout
            // 如果延时不存在，重新设定延时
        if (!timeout) timeout = setTimeout(later, wait)
        if (callNow) {
            result = func.apply(context, args)
            context = args = null
        }

        return result
    }
}
/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
    const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
    if (!search) {
        return {}
    }
    const obj = {}
    const searchArr = search.split('&')
    searchArr.forEach(v => {
        const index = v.indexOf('=')
        if (index !== -1) {
            const name = v.substring(0, index)
            const val = v.substring(index + 1, v.length)
            obj[name] = val
        }
    })
    return obj
}
/* 读取文件 */
export const readFile = (file) => {
    return new Promise(resolve => {
        let reader = new FileReader()
        reader.readAsBinaryString(file)
        reader.onload = ev => {
            resolve(ev.target.result)
        }
    })
}
export const exportExcel = (XLSX, data, filename) => {
    /* 如果没有导入xlsx组件则导入 */
    if (typeof XLSX == 'undefined') XLSX = require('xlsx');
    // 将一个 json 对象转换成一个 sheet 对象
    let sheet = XLSX.utils.json_to_sheet(data);
    // 创建虚拟的 excel 表格（workbook）
    let wb = XLSX.utils.book_new();
    // 把 sheet 添加到 workbook 里
    XLSX.utils.book_append_sheet(wb, sheet, "sheetName");
    // 导出的方法 1（简单版本）
    XLSX.writeFile(wb, filename + ".xlsx");
    // // 导出的方法 2（复杂版本）
    // // 把workbook转成blob
    // let blob = workbook2blob(wb)
    // openDownloadDialog(blob, 'excel的标题.xlsx');
}

export const changeObjKey = async(data, options, objkey1, objkey2) => {
    await data.forEach(item => {
        objkey1.forEach((i, index) => {
            if (options) {
                item[i] = item[objkey2[index]]
                delete item[objkey2[index]]
            } else {
                item[objkey2[index]] = item[i]
                delete item[i]
            }
        })

    })
    return data;
}
export const encrypt = (word, key, iv) => {
    if (!key) {
        key = CryptoJS.enc.Utf8.parse("1890415780934936"); //16位
        iv = CryptoJS.enc.Utf8.parse("5016256957849476");
    }
    let encrypted = "";
    if (typeof word == "string") {
        const srcs = CryptoJS.enc.Utf8.parse(word);
        encrypted = CryptoJS.AES.encrypt(srcs, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
    } else if (typeof word == "object") {
        //对象格式的转成json字符串
        const data = JSON.stringify(word);
        const srcs = CryptoJS.enc.Utf8.parse(data);
        encrypted = CryptoJS.AES.encrypt(srcs, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
    }
    return encrypted.ciphertext.toString();
}
export const decrypt = (word, key, iv) => {
    if (!key) {
        key = CryptoJS.enc.Utf8.parse("1890415780934936"); //16位
        iv = CryptoJS.enc.Utf8.parse("5016256957849476");
    }

    const encryptedHexStr = CryptoJS.enc.Hex.parse(word);
    const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    const decrypt = CryptoJS.AES.decrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
}
export const jiami = (data) => {
    if (data.password) {
        data.password = encrypt(data.password, data.key, data.iv)
    }
    return encrypt(data, )

}
export const jiemi = (data) => {
    data = JSON.parse(decrypt(data))
    if (data.password) {
        data.password = decrypt(data.password, data.key, data.iv)
    }
    return data

}


export function zipImg(file) {
    return new Promise((resolve) => {
        if (file && (file.size / 1024 > 500 || file.type !== 'image/gif')) {
            let img = new Image()
            img.src = file.url
            let cvs = document.createElement('canvas')
            let maxRatio = 0.75 // 大图比率
            let minRatio = 0.8 // 小图比率
            let imgQulity = 0.5 // 图像质量
            img.onload = async function() {
                let ratio = (img.naturalWidth > 1000 || img.naturalHeight > 1000) ? maxRatio : minRatio
                cvs.width = img.naturalWidth * ratio
                cvs.height = img.naturalHeight * ratio
                let ctx = cvs.getContext('2d')
                ctx.drawImage(img, 0, 0, cvs.width, cvs.height)
                    // 压缩后新图的 base64
                let zipBase64 = cvs.toDataURL(file.raw.type, imgQulity)
                let fileFixed = await dataURLtoFile(zipBase64, file.name, file.raw.type)
                resolve(fileFixed)
            }
        } else { resolve(file) }
    })
}



// base64转图片
export function dataURLtoFile(dataurl, filename, mime) {
    return new Promise((resolve) => {
        let arr = dataurl.split(';base64,')
        let suffix = mime.split('/')[1]
        let bstr = atob(arr[1])
        let n = bstr.length
        filename = filename.split(".")[0]
        let u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        let data = new File([u8arr], `${filename}.${suffix}`, {
            type: mime
        })
        resolve(data)
    })
}